package com.cnswhy.cloud.server.core.channel.aliyun;

import com.alibaba.fastjson.JSON;
import com.cnswhy.cloud.server.core.channel.aliyun.dto.IPinfoResponse;
import com.cnswhy.cloud.server.core.channel.aliyun.dto.IpData;
import com.cnswhy.cloud.server.core.channel.verify.util.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class AliyunIpService {
    private static final String appCode = "3ac78dc0a3264ff98dde6e22121cbdbd";
    private static final String hostUrl = "https://ipquery.market.alicloudapi.com";
    public IPinfoResponse getIPinfo(String ip) {
        log.info("enter info getIPinfo:{}", ip);
        String path = "/query";
        String method = "GET";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appCode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("ip", ip);
        IPinfoResponse iPinfoResponse =  null;
        try {
            HttpResponse response = HttpUtils.doGet(hostUrl, path, method, headers, querys);
            System.out.println(response.toString());
            String responseMsg = new String(EntityUtils.toString(response.getEntity()));
            System.out.println(responseMsg);
            iPinfoResponse = JSON.parseObject(responseMsg, IPinfoResponse.class);

            if(iPinfoResponse == null){
                iPinfoResponse = new IPinfoResponse();
                iPinfoResponse.setRet("40001");
                iPinfoResponse.setMsg("网络异常");
            }
            if(!iPinfoResponse.getRet().equals("200")){
                if(StringUtils.isEmpty(iPinfoResponse.getMsg())){
                    iPinfoResponse.setMsg("网络异常");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        log.info("exit verify4:{}", JSON.toJSONString(iPinfoResponse));
        return iPinfoResponse;
    }
    public static void main(String[] args) {
        AliyunIpService aliyunIpService = new AliyunIpService();
        IPinfoResponse iPinfoResponse = aliyunIpService.getIPinfo("183.13.190.173");
        IpData ipData = iPinfoResponse.getData();
        log.info(JSON.toJSONString(ipData));
    }
}
